<?php
App::uses('AppModel', 'Model');
/**
 * UserOrder Model
 *
 * @property SysWebsite $SysWebsite
 * @property User $User
 * @property UserOrderState $UserOrderState
 * @property UserAddress $UserAddress
 * @property SysGettype $SysGettype
 * @property SysLogisticTpl $SysLogisticTpl
 * @property SysPaytype $SysPaytype
 * @property UserOrderPaytype $UserOrderPaytype
 * @property UserOrderList $UserOrderList
 */
class UserOrder extends AppModel {

	public $actsAs = array('Pagination');
/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'ordernum';

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'sys_website_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'user_order_state_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'sys_gettype_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'sys_paytype_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'user_order_paytype_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'SysWebsite' => array(
			'className' => 'SysWebsite',
			'foreignKey' => 'sys_website_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'UserOrderState' => array(
			'className' => 'UserOrderState',
			'foreignKey' => 'user_order_state_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'SysGettype' => array(
			'className' => 'SysGettype',
			'foreignKey' => 'sys_gettype_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'SysLogisticTpl' => array(
			'className' => 'SysLogisticTpl',
			'foreignKey' => 'sys_logistic_tpl_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'SysPaytype' => array(
			'className' => 'SysPaytype',
			'foreignKey' => 'sys_paytype_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
		'UserOrderPaytype' => array(
			'className' => 'UserOrderPaytype',
			'foreignKey' => 'user_order_paytype_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

/**
 * hasMany associations
 *
 * @var array
 */
	public $hasMany = array(
		'UserOrderList' => array(
			'className' => 'UserOrderList',
			'foreignKey' => 'user_order_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

	/**
	 * 分页条件
	 * @author mingxing.zhao@qq.com
	 * @Date 2012-12-20
	 * @return Array
	 */
	function pageParam($action){
		return array(
				"colNames"=>array(
						'ID','来源','摘要','用户','支付方式','配送方式','总价','数量','订单状态','下单时间','操作'
				),
				"colModel"=>array(
						array("name"=>'UserOrder.id',"width"=>'15',"sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.order_source_id',"width"=>'10',"sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.sys_website_id',"sortable"=>false,"align"=>"left"),
						array("name"=>'UserOrder.user_id',"width"=>"25","sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.sys_paytype_id',"width"=>"20","sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.sys_gettype_id',"width"=>"20","sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.price_order',"width"=>"15","sortable"=>true,"align"=>"right"),
						array("name"=>'UserOrder.order_total',"width"=>"15","sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.user_order_state_id',"width"=>"20","sortable"=>true,"align"=>"center"),
						array("name"=>'UserOrder.created',"width"=>"30","sortable"=>true,"align"=>"center"),
						array("name"=>'act',"width"=>"15","sortable"=>false,"align"=>"center")
				),
				"action"=>$action,
				'sortname'=>'id',
				'sortorder'=>'DESC'
		);
	}
	
	/**
	 * 分页数据
	 * @author mingxing.zhao@qq.com
	 * @param array
	 * @date 2013-12-20
	 * @return json
	 *
	 */
	function jsonData($res){
		$rowN = array();
		$i=0;
		foreach($res['rows'] as $k => $value){
			$zy = '';
			foreach ($value['UserOrderList'] as $uol){
				if($uol['showtime']){
					$showtime = '<font color=green>'.date('y/m/d H:i',strtotime($uol['showtime'])).'</font>';
				}else{
					$showtime = '<font color=red>-----时间丢失----</font>';
				}
				$zy.= '<div>'.$uol['Ticket']['title'];
				$zy.= '<span style=float:right>[<font color=red>'.$uol['price_sigle'].'</font>X'.$uol['price_num'].']';
				$zy.=  $showtime;
				$zy.= "</span></div>";
			}
			$rowN[$i]['id'] = $value['UserOrder']['id'];
			$rowN[$i++]['cell'] = array(
					$value['UserOrder']['id'],
					$this->OrderSource($value['UserOrder']['order_source_id']),
					$zy,
					$value['User']['name']==''?'<font color=orange>'.$value['UserOrder']['address_receive'].'</font>':$value['User']['name'],
					$value['SysPaytype']['title'],
					$value['SysGettype']['title'],
					$value['UserOrder']['price_order'],
					$value['UserOrder']['order_total'],
					'<font class=c_'.$value['UserOrderState']['id'].'>'.$value['UserOrderState']['title'].'</font>',
					date('m-d H:i',strtotime($value['UserOrder']['created'])),
					''
			);
		}
		$res['rows'] = $rowN;
		return json_encode($res);
	}
	
	private function OrderSource($id = 0){
		$source = array(
			'0'=>'',
			'1'=>'<font color=blue>电脑</font>',
			'2'=>'<font color=green>微信</font>',
			'3'=>'<font color=pink>移动</font>',
		);
		if(isset($source[$id])){
			return $source[$id];
		}else{
			return '未知';
		}
	}
	
	function updateOrderState($id,$state,$pay_type_id = false,$trade_num = ''){
		$this->id = $id;
		$this->set('trade_no',$trade_num);
		if($pay_type_id){
			$this->set('user_order_paytype_id',$pay_type_id);
		}
		$this->set('user_order_state_id',$state);
		return $this->save(); 
	}
	
	function createOrder($order){
		
		$dataSource = $this->getDataSource();
		$dataSource->begin();
		$err = 0;
		
		//物流费
		$price_logistic = 0;
		$logistic_id = '';
		
		//组织收货地址
		if($order['UserOrder']['sys_gettype_id']==2){
			$order['UserOrder']['address'] = '';
		}else{
			ClassRegistry::init('UserAddress');
			$UserAddress = new UserAddress();
			$radd = $UserAddress->findById($order['UserOrder']['address_id']);
			
			$order['UserOrder']['address_receive'] = $radd['UserAddress']['receiver'];
			$order['UserOrder']['address_phone'] =  $radd['UserAddress']['cellphone'];
			$order['UserOrder']['address'] = $radd['SysProvince']['name'].' '.$radd['SysCity']['name'].' '.$radd['UserAddress']['address'];
			
			ClassRegistry::init('SysLogisticTpl');
			$SysLogisticTpl = new SysLogisticTpl();
			$SysLogisticTpl->recursive = -1;
			$site_id = 1;//$order['UserOrder']['sys_website_id'];
			$p = $radd['UserAddress']['sys_province_id'];
			$c = $radd['UserAddress']['sys_city_id'];
			$slt = $SysLogisticTpl->getSLT($site_id,$p,$c);
			if($slt){
				$logistic_id = $slt['SysLogisticTpl']['id'];
				$price_logistic = $slt['SysLogisticTpl']['price'];
			}else{
				$slt = $SysLogisticTpl->getSLT($site_id,$p);
				if($slt){
					$logistic_id = $slt['SysLogisticTpl']['id'];
					$price_logistic = $slt['SysLogisticTpl']['price'];
				}else{
					$slt = $SysLogisticTpl->findById(1);//默认
					$logistic_id = 1;
					$price_logistic = $slt['SysLogisticTpl']['price'];
				}
				
			}
		}
		
		//票品
		ClassRegistry::init('TicketPrice');
		$TicketPrice = new TicketPrice();
		$TicketPrice->recursive = -1;
		$total = 0;
		$price = 0;
		$delogistic = 0;
		if(count($order['UserOrderList'])>0){
			foreach ($order['UserOrderList'] as $ok => $ol){
				$nol['user_order_id'] = '';
				$tp = $TicketPrice->findById($ol['ticket_price_id']);
				$nol['ticket_price_id'] = $ol['ticket_price'];
				$nol['ticket_id'] = $tp['TicketPrice']['ticket_id'];
				$nol['spt_eticket'] = isset($ol['spt_eticket'])?$ol['spt_eticket']:0;
				if($nol['spt_eticket']==1)$delogistic++;
				$nol['showtime'] = $tp['TicketPrice']['showtime'];
				$nol['price_sigle'] = ($nol['spt_eticket']==1)?$tp['TicketPrice']['eprice']:$tp['TicketPrice']['price'];
				$nol['price_num'] = $ol['price_num'];
				$nol['price_total'] = $nol['price_sigle']*$ol['price_num'];
				$total += $ol['price_num'];
				$price += $nol['price_total'];
				$nol['state'] = 1;
				$order['UserOrderList'][$ok] = $nol;
			}
		}else{
			$err++;
		}
		
		$order['UserOrder']['price_order'] = $price;
		$order['UserOrder']['order_total'] = $total;
		$order['UserOrder']['user_order_state_id'] = 1;
		$order['UserOrder']['sys_logistic_tpl_id'] =$logistic_id;
		if($delogistic == count($order['UserOrderList']))$price_logistic = 0;
		$order['UserOrder']['price_logistic'] = $price_logistic;
		$order['UserOrder']['price_total'] = $price+$price_logistic;
		
		if(!$this->save($order)){
			$err++;
		}else{
			$order_sn = str_pad($this->id,10,0,STR_PAD_LEFT);
			$this->set('ordernum',$order_sn);
			$this->save();
		}
	
		ClassRegistry::init('UserOrderList');
		$UserOrderList = new UserOrderList();
		
		//票品
		if(count($order['UserOrderList'])>0){
			foreach ($order['UserOrderList'] as $ol){
				$UserOrderList->create();
				$ol['user_order_id'] = $this->id;
				if(!$UserOrderList->save($ol)){
					$err++;
				};
			}
		}else{
			$err++;
		}
		
		if($err>0){
			$dataSource->rollback();
			return false;
		}else{
			$dataSource->commit();
			return $this->id;
		}
	}
	
	function createSeatOrder($order){
		$res = array('state'=>false,'msg'=>'','data'=>'');
		$dataSource = $this->getDataSource();
		$dataSource->begin();
		$err = 0;
	
		//物流费
		$price_logistic = 0;
		$logistic_id = '';
	
		$order['UserOrder']['sys_website_id']  =1;
		$order['UserOrder']['order_source_id']  =1;
		//组织收货地址
		if($order['UserOrder']['sys_gettype_id']==2){
			$order['UserOrder']['address'] = '';
		}else{
			ClassRegistry::init('UserAddress');
			$UserAddress = new UserAddress();
			$radd = $UserAddress->findById($order['UserOrder']['address_id']);
	
			$order['UserOrder']['address_receive'] = $radd['UserAddress']['receiver'];
			$order['UserOrder']['address_phone'] =  $radd['UserAddress']['cellphone'];
			$order['UserOrder']['address'] = $radd['SysProvince']['name'].' '.$radd['SysCity']['name'].' '.$radd['UserAddress']['address'];
	
			ClassRegistry::init('SysLogisticTpl');
			$SysLogisticTpl = new SysLogisticTpl();
			$SysLogisticTpl->recursive = -1;
			$site_id = 1;//$order['UserOrder']['sys_website_id'];
			$p = $radd['UserAddress']['sys_province_id'];
			$c = $radd['UserAddress']['sys_city_id'];
			$slt = $SysLogisticTpl->getSLT($site_id,$p,$c);
			if($slt){
				$logistic_id = $slt['SysLogisticTpl']['id'];
				$price_logistic = $slt['SysLogisticTpl']['price'];
			}else{
				$slt = $SysLogisticTpl->getSLT($site_id,$p);
				if($slt){
					$logistic_id = $slt['SysLogisticTpl']['id'];
					$price_logistic = $slt['SysLogisticTpl']['price'];
				}else{
					$slt = $SysLogisticTpl->findById(1);//默认
					$logistic_id = 1;
					$price_logistic = $slt['SysLogisticTpl']['price'];
				}
	
			}
		}
	
		ClassRegistry::init('Seat.Seat');
		$Seat = new Seat();
		ClassRegistry::init('Seat.TicketShowing');
		$TicketShowing = new TicketShowing();
		$total = 0;
		$price = 0;
		$delogistic = 0;
		if(count($order['UserOrderList'])>0){
			foreach ($order['UserOrderList'] as $ok => $ol){
				$nol['user_order_id'] = '';
				$ts = $this->UserOrderList->checkTicketSeat($ol['ticket_showing_id'],$ol['ticket_seat_id']);
				if($ts){
					$err++;
					$msg = $ol['title'].'暂时无法购买';
					break;
				}
				$cSeat = $Seat->findById($ol['ticket_seat_id']);
				
				$ts = $TicketShowing->findById($ol['ticket_showing_id']);
				
				$nol['ticket_id'] = $ol['ticket_id'];
				$nol['ticket_showing_id'] = $ol['ticket_showing_id'];
				$nol['ticket_seat_id'] = $ol['ticket_seat_id'];
				$nol['ticket_seat_sold_id'] = $ol['ticket_seat_sold_id'];
				$nol['ticket_price_id'] = 0;
				$nol['seat'] = $ol['title'];
				$nol['showtime'] = $ts['TicketShowing']['showtime'];
				$nol['spt_eticket'] = 0;
				$nol['price_sigle'] = $cSeat['SeatType']['price'];
				$nol['price_num'] = 1;
				$nol['price_total'] = $nol['price_sigle']*$ol['price_num'];
				$total += $ol['price_num'];
				$price += $nol['price_total'];
				$nol['state'] = 1;
				$order['UserOrderList'][$ok] = $nol;
			}
		}else{
			$err++;
			$msg = '订单列表为空';
		}
		if($err>0){
			$res['state'] = false;
			$res['msg'] = $msg;
			return $res;
		}
		$order['UserOrder']['price_order'] = $price;
		$order['UserOrder']['order_total'] = $total;
		$order['UserOrder']['user_order_state_id'] = 1;
		$order['UserOrder']['sys_logistic_tpl_id'] =$logistic_id;
		if($delogistic == count($order['UserOrderList']))$price_logistic = 0;
		$order['UserOrder']['price_logistic'] = $price_logistic;
		$order['UserOrder']['price_total'] = $price+$price_logistic;
		
		if(!$this->save($order)){
			$err++;
			$msg = '订单保存失败';
		}else{
			$order_sn = str_pad($this->id,10,0,STR_PAD_LEFT);
			$this->set('ordernum',$order_sn);
			$this->save();
		}
	
		ClassRegistry::init('UserOrderList');
		$UserOrderList = new UserOrderList();
	
		//票品
		if($err == 0){
			if(count($order['UserOrderList'])>0){
				foreach ($order['UserOrderList'] as $ol){
					$UserOrderList->create();
					$ol['user_order_id'] = $this->id;
					if(!$UserOrderList->save($ol)){
						$err++;
						$msg = '订单列表保存失败';
					};
				}
			}else{
				$err++;
				$msg = '订单列表为空';
			}
		}
	
		if($err>0){
			$dataSource->rollback();
			$res['state'] = false;
			$res['msg'] = $msg;
			return $res;
		}else{
			$dataSource->commit();
			$res['state'] = true;
			$res['msg'] = 'success';
			$res['data'] = $this->id;
			return $res;
		}
	}
}
